#include <QDebug>
#include "taskmanager.h"

TaskManager::TaskManager()
{
}

void TaskManager::getTasks(int limit, int offset, QString filterSpaceTag,
                           QString filterId, QString searchKey)
{
    qDebug() << ">>>TaskManager::getTasks<<<";
    CVSession *session = CVSession::get();
    QString sessionId = session->getSessionId();
    if (!sessionId.isNull() && !sessionId.isEmpty())
    {
        QString network = session->getCurrentNetwork()->getUrl();
        QUrl url = CVUtil::getBaseUrl("mobile.get_tasks", network);
        url.addQueryItem("view_param", filterSpaceTag);
        url.addQueryItem("simpletype", filterId);
        url.addQueryItem("limit", QString::number(limit));
        url.addQueryItem("offset", QString::number(offset));
        url.addQueryItem("lang", "en");
        url.addQueryItem("search", searchKey);
        CVHttp *http = new CVHttp(url);
        //http->setDebug(true);
        connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(parseData(QScriptValue,QString)));
    }
}

void TaskManager::parseData(QScriptValue json, const QString &msg)
{
    QList<Task *> list;
    if (!json.isNull() && !json.isError())
    {
        QScriptValueIterator it(json);
        while (it.hasNext())
        {
            it.next();
            QScriptValue value = it.value();
            Task *task = new Task();
            if (!value.property("guid").toString().isEmpty())
            {
                task->setAttribute(Task::GUID, value.property("guid").toString());
                task->setAttribute(Task::TITLE, value.property("title").toString());
                task->setAttribute(Task::DUEDATE, value.property("duedate").toString());
                task->setAttribute(Task::CREATOR, value.property("creator").toString());
                task->setAttribute(Task::CREATOR_ID, value.property("creator_id").toString());
                task->setAttribute(Task::MY_STATUS, value.property("my_status").toString());
                task->setAttribute(Task::STATUS_STRING, value.property("status_string").toString());
                list.append(task);
            }
        }
    }
    emit handleTasks(list);
}
